public class BinarySearchTree {

    static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    public TreeNode root ;

    public void insert(int key) {
        if(root == null){
            root = new TreeNode(key);
            return;
        }
        TreeNode parent = null;
        TreeNode cur = root;
        TreeNode node = new TreeNode(key);
        while(cur != null){
            parent = cur;
            if(cur.val > key){
                cur = cur.left;
            }else if(cur.val < key) {
                cur = cur.right;
            }else {
                    return;
            }
            if( parent.val > key){
                parent.left = node;
            }else {
                parent.right = node;
            }

        }
    }

    public TreeNode search(TreeNode root, int val) {
        if(root == null || root.val == val){
            return root;
        }else if(root.val > val){
           return search(root.left,val);
        }else {
           return search(root.right,val);
        }
    }
    public TreeNode search(int val) {
        TreeNode cur = root;
        while (cur != null){
            if(cur.val == val){
                return cur;
            }else if(cur.val > val){
                cur = cur.left;
            }else {
                cur = cur.right;
            }
        }
        return null;
    }

    private void removeNode(TreeNode parent, TreeNode cur){
        if(cur.left == null){
            if(cur == root){
                root = cur.right;
            }else if(parent.left == null){
                parent.right = cur.right;
            }else if(parent.right == null){
                parent.left = cur.right;
            }
        }else if(cur.right == null){
            if(cur == root){
                root = cur.left;
            }else if(parent.left == null){
                parent.right = cur.left;
            }else if(parent.right == null){
                parent.left = cur.left;
            }
        }else{
            TreeNode tar = cur.right;
            TreeNode tarPre = cur;
            while(tar.left != null){
                tarPre = tar;
                tar = tar.left;
            }
            cur.val = tar.val;
            if(tarPre.right == tar){
                tarPre.right = tar.right;
                return;
            }
            tarPre.left = tar.right;
        }
    }

}